package com.cetool.autocms.service.sys.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cetool.autocms.enumeration.OperateEnum;
import com.cetool.autocms.mapper.sys.MenuMapper;
import com.cetool.autocms.mapper.sys.PermissionMapper;
import com.cetool.autocms.mapper.sys.RoleMapper;
import com.cetool.autocms.pojo.domain.sys.MenuInfoDO;
import com.cetool.autocms.pojo.dto.sys.MenuCheckBoxDTO;
import com.cetool.autocms.pojo.dto.sys.RoleSelectDTO;
import com.cetool.autocms.pojo.param.sys.QueryRolePermissionParam;
import com.cetool.autocms.pojo.param.sys.SaveRolePermissionParam;
import com.cetool.autocms.pojo.request.sys.QueryRolePermissionRequest;
import com.cetool.autocms.pojo.request.sys.SaveRolePermissionRequest;
import com.cetool.autocms.service.sys.PermissionService;
import com.cetool.autocms.util.BeansUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限管理服务实现层
 *
 * @author 戴越
 * @date 2021/11/25
 */
@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {
    /**
     * 注入菜单管理持久层
     */
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 注入角色管理持久层
     */
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 注入权限管理持久层
     */
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<RoleSelectDTO> queryRoleSelect() {
        return BeansUtil.listCopy(roleMapper.getRoleSelectList(), RoleSelectDTO.class);
    }

    @Override
    public List<MenuCheckBoxDTO> queryMenuCheckBox() {
        List<MenuInfoDO> allMenuList = menuMapper.getAllMenuList();
        Map<Integer, List<MenuInfoDO>> collect = allMenuList.stream().collect(Collectors.groupingBy(MenuInfoDO::getPid));
        List<MenuCheckBoxDTO> menuListS = BeansUtil.listCopy(collect.get(-1), MenuCheckBoxDTO.class);
        for (MenuCheckBoxDTO list : menuListS) {
            list.setChildren(collect.get(list.getId()));
        }
        return menuListS;
    }

    @Override
    public List<Integer> queryRolePermission(QueryRolePermissionRequest request) {
        QueryRolePermissionParam param = new QueryRolePermissionParam();
        BeanUtil.copyProperties(request, param);
        return permissionMapper.queryRolePermission(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperateEnum saveRolePermission(SaveRolePermissionRequest request) {
        SaveRolePermissionParam param = new SaveRolePermissionParam();
        BeanUtil.copyProperties(request, param);
        //1、先删除该角色小所有菜单关联；
        permissionMapper.deleteRolePermission(param);
        //2、插入菜单关联
        permissionMapper.saveRolePermission(param);
        return OperateEnum.ADD_SUCCESS;
    }

}
